<template>
  <ProjectBaseInfo />
  <div class="bg-white my-[10px]">
    <BaseHead style="border-bottom: 0">预算明细（单位：万元）</BaseHead>
    <el-table
      :data="budgetList"
      stripe
      class="w-full"
      border
      row-key="subjectId"
      default-expand-all
      :tree-props="{ hasChildren: 'hasChild' }"
      show-summary
      :summary-method="summaryFn"
    >
      <el-table-column type="index" label="序号" width="60px" />
      <el-table-column prop="subjectName" label="预算科目"> </el-table-column>
      <el-table-column prop="feeRatio" label="经费占比">
        <template #default="{ row }">
          {{ row.feeRatio + "%" }}
        </template>
      </el-table-column>
      <el-table-column prop="subjectFee" label="预算经费">
        <template #default="{ row }">
          <div v-if="row.children.length">{{ row.subjectFee }}</div>
          <el-input
            v-model="row.subjectFee"
            clearable
            @input="valueChange(row, $event)"
            v-else
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="备注">
        <template #default="{ row }">
          <el-input placeholder="" clearable v-model="row.note" />
        </template>
      </el-table-column>
      <el-table-column prop="subjectNote" label="预算科目说明"> </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import ProjectBaseInfo from "./ProjectBaseInfo.vue";
import { sbBudgetDetail, sbBudget } from "@/api/project/xj/sbxm";
import { ElMessage } from "element-plus";
import { fomateNumber, fiexdNumber } from "@/utils/main";
const operateId = ref(null);
const budgetList = ref([]);
const applyFee = ref(0); //申请经费
const isAuditor = inject("isAuditor");
const taskId = inject("taskId");
const checkStatus = inject("checkStatus");
//获取预算信息详情
const getBudgetDetail = async () => {
  const params = {
    applyBookId: operateId.value,
  };
  try {
    const res = await sbBudgetDetail(params);
    budgetList.value = res.data.budget;
    applyFee.value = res.data.applyFee ? parseFloat(res.data.applyFee) : 0;
  } catch (error) {
    console.log(error);
  }
};
//编辑
const edit = async (id) => {
  operateId.value = id;
  getBudgetDetail();
};
//输入的预算经费改变
const valueChange = (row, val) => {
  fomateNumber(row, "subjectFee", val);
  if (!row.subjectFee) {
    row.subjectFee = 0;
  }
  nextTick(() => {
    row.feeRatio = Math.round((parseFloat(row.subjectFee) / applyFee.value) * 10000) / 100;
    const updateParentMoney = (nodes) => {
      return nodes.map((node) => {
        // 如果有子节点，则递归处理子节点
        if (node.children && node.children.length > 0) {
          const updatedChildren = updateParentMoney(node.children);
          const sumFee = updatedChildren.reduce((acc, cur) => {
            return acc + (cur.subjectFee ? parseFloat(cur.subjectFee) : 0);
          }, 0);
          const sumFeeRatio = updatedChildren.reduce((acc, cur) => {
            return acc + (cur.feeRatio ? parseFloat(cur.feeRatio) : 0);
          }, 0);
          return {
            ...node,
            subjectFee: fiexdNumber(sumFee, 6),
            feeRatio: fiexdNumber(sumFeeRatio),
            children: updatedChildren,
          };
        }
        // 没有子节点则直接返回
        return node;
      });
    };
    budgetList.value = updateParentMoney(budgetList.value);
  });
};
//合计方法
const summaryFn = ({ columns, data }) => {
  const sums = [];
  columns.forEach((column, index) => {
    if ([0, 4, 5].includes(index)) {
      sums[index] = "";
    } else if (index == 1) {
      sums[index] = "合计";
    } else {
      let total = 0;
      data.forEach((item) => {
        total += parseFloat(item[column.property]);
      });
      if (index == 2) {
        sums[index] = fiexdNumber(total) + "%";
      } else {
        sums[index] = fiexdNumber(total, 6);
        //如果输入的经费合计等于总经费 则经费占比置为100 防止出现100.1% 这类情况
        if (fiexdNumber(total, 6) == applyFee.value) {
          sums[index - 1] = "100%";
        }
      }
    }
  });
  return sums;
};
const emit = defineEmits(["save-success", "save-ok"]);
//保存
const save = async (submitType) => {
  try {
    //判断预算信息是否为空
    if (!budgetList.value.length) {
      ElMessage({
        message: "请填写预算信息！",
        type: "error",
      });
      return;
    }
    //判断填写的预算总经费是否与项目总经费相等
    let total = 0;
    budgetList.value.forEach((item) => {
      total += parseFloat(item.subjectFee);
    });
    //判断预算经费合计是否与总经费相等
    if (fiexdNumber(total, 6) != applyFee.value) {
      ElMessage({
        message: "预算合计不等于申请经费，请调整！",
        type: "error",
      });
      return;
    }
    const budgets = [];
    const getParams = (rows) => {
      for (let i = 0; i < rows.length; i++) {
        budgets.push({
          id: rows[i].id,
          subjectId: rows[i].subjectId,
          subjectCode: rows[i].subjectCode,
          subjectName: rows[i].subjectName,
          subjectFee: rows[i].subjectFee,
          note: rows[i].note,
          feeRatio: rows[i].feeRatio,
          upCode: rows[i].upCode,
          subjectNote: rows[i].subjectNote,
        });
        if (rows[i].children) {
          getParams(rows[i].children);
        }
      }
    };
    getParams(budgetList.value);
    let params = {
      id: operateId.value,
      budgets,
      submitType,
      isAuditor: isAuditor.value,
      taskId: taskId.value,
      checkstatus: checkStatus.value,
    };
    const res = await sbBudget(params);
    if (res.code === 200) {
      emit("save-success");
    }
  } catch (error) {
    console.log(error);
  } finally {
    emit("save-ok");
  }
};
defineExpose({ edit, save });
</script>

<style scoped lang="scss"></style>
